using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BanZuiCloudControlAgent.Utils.Exceptions;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.Core.Mqtt.Listener
{
    /// <summary>
    /// MQTT消息监听器，负责监听MQTT消息
    /// </summary>
    public class MqttMessageListener
    {
        private readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly MqttClientManager _clientManager;
        private readonly MqttMessageHandler _messageHandler;
        private bool _isListening;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="clientManager">MQTT客户端管理器</param>
        /// <param name="messageHandler">MQTT消息处理器</param>
        public MqttMessageListener(MqttClientManager clientManager, MqttMessageHandler messageHandler)
        {
            _clientManager = clientManager ?? throw new ArgumentNullException(nameof(clientManager));
            _messageHandler = messageHandler ?? throw new ArgumentNullException(nameof(messageHandler));
            _isListening = false;
        }

        /// <summary>
        /// 启动监听
        /// </summary>
        public void Start()
        {
            try
            {
                if (_isListening)
                {
                    _logger.Warn("MQTT消息监听器已经在运行中");
                    return;
                }

                // 订阅消息接收事件
                _clientManager.MessageReceived += OnMessageReceived;
                _isListening = true;

                _logger.Info("MQTT消息监听器已启动");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "启动MQTT消息监听器失败");
                throw new EmqxException(EmqxErrorType.ListenerStartFailed, null, "启动MQTT消息监听器失败", ex);
            }
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        public void Stop()
        {
            try
            {
                if (!_isListening)
                {
                    _logger.Warn("MQTT消息监听器未在运行");
                    return;
                }

                // 取消订阅消息接收事件
                _clientManager.MessageReceived -= OnMessageReceived;
                _isListening = false;

                _logger.Info("MQTT消息监听器已停止");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "停止MQTT消息监听器失败");
                throw new EmqxException(EmqxErrorType.ListenerStopFailed, null, "停止MQTT消息监听器失败", ex);
            }
        }

        /// <summary>
        /// 消息接收事件处理
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnMessageReceived(object sender, MqttMessageReceivedEventArgs e)
        {
            try
            {
                _logger.Debug($"收到来自主题 {e.Topic} 的消息");

                // 将消息转发给消息处理器
                _messageHandler.HandleMessage(e.Topic, e.PayloadString);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"处理接收到的MQTT消息失败: {ex.Message}");
            }
        }
    }
} 